import Vue from "vue";
import axios from "axios";
import { Dialog } from "vant";
import store from "@/store";
import { Tip } from "@/utils";
import { ACCESS_TOKEN, TENANT_ID } from "@/store/mutation-types";
import { login } from "@/utils/login";
import { apiBaseUrl } from "@/utils/request";
Vue.use(Dialog);
const produce = axios.create({
  baseURL: apiBaseUrl, // api base_url
  timeout: 9000, // 请求超时时间
});
let prefixConfig = '/jksaas-produce/produce'

const err = (error) => {
  if (error.response) {
    if (error.response.status == 200) {
      console.log("code为 200 ");
    } else {
      if (error.response.data.message.includes("Token失效")) {
        login()
          .then((res) => {
            window.location.reload();
          })
          .catch((e) => {
            if (e && e.rejectType == "browser") {
              store.dispatch("Logout").then(() => {
                Vue.ls.remove(ACCESS_TOKEN);
                window.location.reload();
              });
            }
          });
      } else {
        Tip.error(response.data.message);
      }
    }
  }
  return Promise.reject(error);
};

// request interceptor
produce.interceptors.request.use(
  (config) => {
    let prefix = prefixConfig
    let slash = config.url.charAt(0) == '/'
    config.url = apiBaseUrl + prefix + `${slash ? config.url : '/'+config.url}`;
    const token = Vue.ls.get(ACCESS_TOKEN);
    if (token) {
      config.headers["X-Access-Token"] = token; // 让每个请求携带自定义 token 请根据实际情况自行修改
    }
    //update-begin-author:taoyan date:2020707 for:多租户
    let tenantid = Vue.ls.get(TENANT_ID);
    if (!tenantid) {
      tenantid = 0;
    }
    config.headers["tenant_id"] = tenantid;
    //update-end-author:taoyan date:2020707 for:多租户
    if (config.method == "get") {
      if (config.url.indexOf("sys/dict/getDictItems") < 0) {
        config.params = {
          _t: Date.parse(new Date()) / 1000,
          ...config.params,
        };
      }
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// response interceptor
produce.interceptors.response.use((response) => {
  return response.data;
}, err);

/**
 * Blob解析
 * @param data
 */
function blobToJson(data) {
  let fileReader = new FileReader();
  let token = Vue.ls.get(ACCESS_TOKEN);
  fileReader.onload = function() {
    try {
      let jsonData = JSON.parse(this.result); // 说明是普通对象数据，后台转换失败
      console.log("jsonData", jsonData);
      if (jsonData.status === 500) {
        console.log("token----------》", token);
        if (token && jsonData.message.includes("Token失效")) {
          store.dispatch("Logout").then(() => {
            Vue.ls.remove(ACCESS_TOKEN);
            window.location.reload();
          });
        }
      }
    } catch (err) {
      // 解析成对象失败，说明是正常的文件流
      console.log("blob解析fileReader返回err", err);
    }
  };
  fileReader.readAsText(data);
}

export { produce, prefixConfig };
